<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validateTrigger="bind">
			<uni-forms-item name="name" label="名称" required>
				<uni-easyinput placeholder="名称" v-model="formData.name" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="nickname" label="昵称">
				<uni-easyinput placeholder="昵称" v-model="formData.nickname" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="description" label="描述">
				<uni-easyinput placeholder="描述" v-model="formData.description" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="tabs" label="标签" required>
				<uni-easyinput placeholder="标签" v-model="formData.tabs" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="class_id" label="分类" required>
				<uni-data-picker v-model="formData.class_id" collection="product_wallpaper_class" field="_id as value, classname as text"></uni-data-picker>
			</uni-forms-item>
			<uni-forms-item name="score" label="系统评分" required>
				<uni-rate v-model="formData.score" :max="5" allow-half />
			</uni-forms-item>
			<uni-forms-item name="sort" label="排序">
				<uni-easyinput placeholder="排序" type="number" v-model="formData.sort"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="view_count" label="浏览量">
				<uni-easyinput placeholder="浏览量" type="number" v-model="formData.view_count"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="select" label="是否推荐" required>
				<switch @change="binddata('select', $event.detail.value)" :checked="formData.select"></switch>
			</uni-forms-item>
			<uni-forms-item name="picurl" label="图片" required>
				<uni-file-picker file-mediatype="image" :auto-upload="false" @select="handleFileSelect" return-type="object" v-model="formData.picurl"></uni-file-picker>
			</uni-forms-item>
			<uni-forms-item name="del_status" label="是否删除">
				<switch @change="binddata('del_status', $event.detail.value)" :checked="formData.del_status"></switch>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px" @click="submit" :disabled="!canSubmit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px">
					<button class="uni-button" style="width: 100px">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
import { validator } from '@/js_sdk/product_wallpaper/list.js';
import { getCurYMD, getUser, uploadFileToDir } from '../utils.js';

const db = uniCloud.database();
const dbCmd = db.command;
const dbCollectionName = 'product_wallpaper_list';

function getValidator(fields) {
	let result = {};
	for (let key in validator) {
		if (fields.includes(key)) {
			result[key] = validator[key];
		}
	}
	return result;
}

export default {
	data() {
		let formData = {
			name: '',
			nickname: '',
			description: '',
			tabs: '',
			class_id: '',
			score: 0,
			sort: null,
			view_count: null,
			select: false,
			picurl: null,
			del_status: null
		};
		return {
			canSubmit: false,
			formData,
			formOptions: {},
			rules: {
				...getValidator(Object.keys(formData))
			}
		};
	},
	onReady() {
		this.$refs.form.setRules(this.rules);
	},
	methods: {
		/**
		 * 手动上传文件
		 */
		async handleFileSelect(fileInfo) {
			uploadFileToDir(
				fileInfo,
				`wallpaper/${getCurYMD()}`,
				(fileUrl) => {
					this.formData.picurl = fileUrl;
				},
				(percentCompleted) => {
					this.canSubmit = percentCompleted === 100;
				}
			);
		},
		/**
		 * 验证表单并提交
		 */
		submit() {
			uni.showLoading({
				mask: true
			});
			this.$refs.form
				.validate()
				.then((res) => {
					res.user_id = getUser();
					return this.submitForm(res);
				})
				.catch(() => {})
				.finally(() => {
					uni.hideLoading();
				});
		},

		/**
		 * 提交表单
		 */
		submitForm(value) {
			// 使用 clientDB 提交数据
			return db
				.collection(dbCollectionName)
				.add(value)
				.then((res) => {
					uni.showToast({
						title: '新增成功'
					});
					this.updateClassbyId(value.class_id);
					this.getOpenerEventChannel().emit('refreshData');
					setTimeout(() => uni.navigateBack(), 500);
				})
				.catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					});
				});
		},
		// 更新该图片对应的分类的更新时间
		updateClassbyId(classId) {
			db.collection('product_wallpaper_class')
				.doc(classId)
				.update({
					update_time: Date.now()
				})
				.then((res) => {
					console.log(res);
				});
		}
	}
};
</script>
